/*
 * www.qwfys.org Inc.
 * Copyright (c) 2004-2017 All Rights Reserved.
 */
package org.qwfys.netty.core;

import java.util.Date;

/**
 * Created by David on 2017/5/15.
 */
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 
 * 
 * 
 * @author lwk
 * @version $Id: SampleClientHandler.java, v 0.1 2017-06-21 00:26:47 lwk Exp$
 */
public class SampleClientHandler extends ChannelInboundHandlerAdapter {

    private final ByteBuf firstMessage;
    static int            nCount = 0;

    public SampleClientHandler() {
        firstMessage = Unpooled.buffer(SampleClient.SIZE);
        for (int i = 0; i < firstMessage.capacity(); i++) {
            firstMessage.writeByte((byte) i);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Date startTime = new Date();
        System.out.println("开始发送时间点：" + startTime);
        ctx.writeAndFlush(firstMessage);
        Date endTime = new Date();
        long haoshi = endTime.getTime() - startTime.getTime();
        System.out.println("结束发送时间点：" + endTime + ", 耗时 : " + haoshi + "毫秒");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //System.out.println("Client Received message : " + msg);
        ctx.write(msg);
        nCount++;
        System.out.println(nCount);
        if (nCount == 100000) {
            System.out.println("***************");
            ctx.close();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
